import numpy as np
from app.models.ecological_indicator import EcologicalIndicator
from app.models.industry_score import IndustryScore

def calculate_comprehensive_score(area):
    """计算海域综合评分"""
    # 获取最新的生态指标
    latest_indicator = EcologicalIndicator.query.filter_by(
        marine_area_id=area.id
    ).order_by(EcologicalIndicator.measurement_date.desc()).first()
    
    if not latest_indicator:
        return None
        
    # 生态指标权重
    weights = {
        'water_quality': 0.3,
        'biodiversity': 0.2,
        'pollution_index': 0.2,
        'resource_reserve': 0.15,
        'environmental_capacity': 0.15
    }
    
    # 计算加权得分
    score = sum(
        float(getattr(latest_indicator, key)) * weight
        for key, weight in weights.items()
    )
    
    return score

def analyze_industry_trends(area):
    """分析产业发展趋势"""
    scores = IndustryScore.query.filter_by(marine_area_id=area.id).all()
    if not scores:
        return {}
        
    # 按产业类型分组
    industry_scores = {}
    for score in scores:
        if score.industry_type not in industry_scores:
            industry_scores[score.industry_type] = []
        industry_scores[score.industry_type].append({
            'date': score.evaluation_date.strftime('%Y-%m-%d'),
            'score': float(score.score)
        })
        
    # 计算趋势
    trends = {}
    for industry, scores in industry_scores.items():
        sorted_scores = sorted(scores, key=lambda x: x['date'])
        scores_array = np.array([s['score'] for s in sorted_scores])
        
        if len(scores_array) > 1:
            # 计算变化率
            change_rate = (scores_array[-1] - scores_array[0]) / scores_array[0]
            # 计算标准差
            std_dev = np.std(scores_array)
            
            trends[industry] = {
                'change_rate': float(change_rate),
                'volatility': float(std_dev),
                'current_score': float(scores_array[-1]),
                'historical_scores': sorted_scores
            }
            
    return trends 